# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from datetime import datetime
from django.shortcuts import render
from django.views import View
from django.conf import settings
from alipay import AliPay
import os
from django.shortcuts import render

# Create your views here.
# orders.views
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse,HttpResponseRedirect
from apps.homes.models import House
from apps.orders.models import Order
from ihome_team7.utils.snowflakes import SnowFlake
import json,re
# Create your views here.
class AddOrdersView(View):
    def post(self,request):
        # 接受参数
        data_dict = json.loads(request.body.decode())
        house_id = data_dict.get('house_id')
        start_date = data_dict.get('start_date')
        end_date = data_dict.get('end_date')

        # 校验参数
        if not all([house_id,start_date,end_date]):
            return JsonResponse({'errno':'4101','errmsg':'参数不全'})

        # 验证是否登录
        if not request.user.is_authenticated:
            return JsonResponse({'errno':'4101','errmsg':'未登录'})
        else:
            # 使用雪花算法生成唯一订单id
            order_id = SnowFlake().get_id()

            # 返回的data参数
            data = {'order_id':order_id}
            # 存储订单_id
            #　取出对应房屋信息
            house = House.objects.get(id=house_id)
            # 验证是否为自己的房屋信息
            if request.user.id != house.user_id:
                # 验证时间段是否有人预定
                orders = Order.objects.filter(house_id=house_id)
                # 判断时间段是否重复
                # end_date=datetime.strptime(end_date,'%Y-%m-%d')
                # start_date = datetime.strptime(start_date, '%Y-%m-%d')
                for order in orders:
                    if end_date > str(order.begin_date) and end_date < str(order.end_date):
                        return JsonResponse({'errno':'4004','errmsg':'日期已被预订'})
                    if start_date > str(order.begin_date) and start_date < str(order.end_date):
                        return JsonResponse({'errno':'4004','errmsg':'日期已被预订'})
                # 判断日期是否合法
                days = SnowFlake.days(start_date,end_date)
                if days <= 0:
                    return JsonResponse({'errno':'4004','errmsg':'日期错误'})
                else:
                    # 验证通过后创建订单并添加进订单数据库
                    order=Order.objects.create(
                    user = request.user,
                    house = house,
                    begin_date = start_date,
                    end_date = end_date,
                    days = days,
                    house_price = house.price,
                    amount = house.price*days,
                    order_id = order_id
                    )
                    pass
                    return JsonResponse({'data':data,'errno':'0','errmsg':'下单成功',})
            else:
                return JsonResponse({'errno': '0', 'errmsg': '不能下单自己', 'data':{}})

    def get(self,request):
        ''''
        获取订单列表
        '''
        # 接受参数,并判断身份
        request_str = request.GET
        role = request.GET.get('role')
        # 房客订单接口
        if re.match('^custom$',role):
            #　查询出该房客用户的所有订单信息
            user=request.user
            orders_mix = Order.objects.filter(user_id=user.id)
            # 建立空data字典
            data = {}
            orders = []
            # 取出每个订单数据
            for order in orders_mix:
                # 取出订单对应房屋对象
                order_dict = {}
                house = House.objects.get(id=order.house_id)
                # 将前段请求信息添加进data
                order_dict['amount'] = order.amount
                order_dict['comment'] = order.comment
                order_dict['ctime'] = SnowFlake.ctime()
                order_dict['days'] = order.days
                order_dict['end_date'] = order.end_date
                order_dict['img_url'] = house.index_image_url
                # 保存唯一订单编号
                order_dict['order_id'] = order.order_id
                order_dict['start_date'] = order.begin_date
                order_dict['status'] = order.status
                order_dict['title'] = house.title
                orders.append(order_dict)

            data['orders'] = orders
            return JsonResponse({'data':data,'errmsg':'ok','errno':'0'})

        # 房东订单接口
        if re.match('^landlord$',role):
            # 找出房主的所有房屋
            houses = House.objects.filter(user_id=request.user.id)
            data = {}
            orders = []
            # 找出每个房屋对应的订单信息
            for house in houses:
                # 取出没个房屋的所有订单信息
                orders_mix = Order.objects.filter(house_id=house.id)
                # 取出每个房屋的每个订单信息
                for order in orders_mix:
                    # 取出每个订单对应房屋对象(因复制而造成的多余操作)
                    order_dict = {}
                    house = House.objects.get(id=order.house_id)
                    # 添加data
                    order_dict['amount'] = order.amount
                    order_dict['comment'] = order.comment
                    order_dict['ctime'] = SnowFlake.ctime()
                    order_dict['days'] = order.days
                    order_dict['end_date'] = order.end_date
                    order_dict['img_url'] = house.index_image_url
                    # 保存订单编号
                    order_dict['order_id'] = order.order_id
                    order_dict['start_date'] = order.begin_date
                    order_dict['status'] = order.status
                    order_dict['title'] = house.title
                    orders.append(order_dict)

            data['orders'] = orders
            return JsonResponse({'data': data, 'errmsg': 'ok', 'errno': '0'})





class AgreeOrderView(View):
    # 房主接受订单信息后选择是否接单
    def put(self,request,order_id):
        # action = request.GET.get('action')
        get_dict = json.loads(request.body.decode())
        action = get_dict['action']
                #　接单选择
        if re.match('^accept$',action):
            # 这里status为3→待评价，省略了支付模块
            Order.objects.filter(order_id=order_id).update(status=1)
            return JsonResponse({'errno':'0','errmsg':'操作成功'})
        # 拒绝接单选择
        elif re.match('^reject$',action):
            reason = get_dict['reason']
            # 这里status为6→已拒绝，省略了支付模块，并为该订单添加拒绝原因
            Order.objects.filter(order_id=order_id).update(status=6,comment=reason)
            return JsonResponse({'errno': '0', 'errmsg': '操作成功'})

class CommitOrderView(View):
    def put(self,request,order_id):
        request_dict = json.loads(request.body.decode())
        comment = request_dict.get('comment')
        # 身份验证
        if not request.user.is_authenticated:
            return JsonResponse({'errno':'4101','errmsg':'未登录'})

        # 给已完成的订单添加评论数据
        order = Order.objects.filter(order_id=order_id)
        if order[0].status == 3:
            order.update(status=4,comment=comment)
            # 该房屋的订单完成数+1
            house = House.objects.filter(id=order[0].house_id)
            new_count = house[0].order_count+1
            house.update(order_count=new_count)
            return JsonResponse({"errno": "0","errmsg": "评论成功"})

        else:
            return JsonResponse({'errno':'4001','errmsg':'订单状态异常'})

class PayView(View):
    def get(self,request,order_id):
        # 1、使用alipay的sdk和阿里交互获取扫码支付页面链接
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 支付成功之后阿里云回调地址
            app_private_key_path=os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'keys/app_private_key.pem'
            ),
            alipay_public_key_path=os.path.join(
                os.path.dirname(os.path.abspath(__file__)),
                'keys/alipay_public_key.pem'
            ),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        order = Order.objects.get(order_id=order_id)

        # alipay.api_alipay_trade_app_pay() --> 用于移动端支付链接
        query_string = alipay.api_alipay_trade_page_pay(
            # 付款主题
            subject="爱家租房订单：%s" % order_id,
            # 美多商城的订单号
            out_trade_no=str(order_id),
            # 订单付款总价
            total_amount=float(order.amount),
            # 重要！return_url指定用户付款成功之后，重定向回美多的链接
            return_url=settings.ALIPAY_RETURN_URL
        )

        # 阿里支付的url是固定的，我们需要在这个url尾部拼接查询字符串
        # 参数，来记录用户的美多商城订单等信息
        alipay_url = settings.ALIPAY_URL + "?" + query_string
        # 2、构建响应返回给用户
        return JsonResponse({'errno':9,'alipay_url':alipay_url})

class PaymentStatusView(View):
    def put(self, request):
        # 分别取出查询字典和signature
        data_dict = request.GET.dict()
        signature = data_dict.pop('sign')

        # 取出alipay对象
        alipay = AliPay(appid=settings.ALIPAY_APPID,
                        app_notify_url=None,  # 默认回调url
                        app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                          "keys/app_private_key.pem"),
                        alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                            "keys/alipay_public_key.pem"),
                        sign_type="RSA2",
                        debug=settings.ALIPAY_DEBUG
                        )

        # 检验是否是回传的data
        success_info = alipay.verify(data_dict, signature)
        # if success_info:
            # 如果验证成功则更改order属性

        order_id = data_dict.get('out_trade_no')
        # trade_id = data_dict.get('trade_no')
        # 取出order对象,修改状态
        order = Order.objects.get(order_id=order_id)
        order.status=3
        order.save()

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'order_id': order_id})
        # else:
        #     # 订单支付失败，重定向到我的订单
        # return JsonResponse({'code': 400, 'errmsg': '非法请求'})


